package com.chen.music.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.music.model.*;
import com.chen.music.service.*;
import com.chen.music.util.CommonResult;
import com.chen.music.util.MessageConst;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 歌手 前端控制器
 * </p>
 *
 * @author boat
 * @since 2022-01-13
 */
@RestController
@RequestMapping("/singer")
@Api(tags = "歌手管理")
public class SingerController {

    @Autowired
    private SingerService singerService;

    @Autowired
    private SongService songService;

    @Autowired
    private ListSongService listSongService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private CollectService collectService;

    @PostMapping("/add")
    @ApiOperation("新增歌手")
    public CommonResult add(Singer singer) {
        try {
            if (singerService.save(singer)) {
                return new CommonResult(200, true, MessageConst.ADD_SINGER_SUCCESS);
            }
            return new CommonResult(200, false, MessageConst.ADD_SINGER_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @PutMapping("/update")
    @ApiOperation("更新歌手")
    public CommonResult update(Singer singer) {
        try {
            if (singerService.updateById(singer)) {
                return new CommonResult(200, true, MessageConst.UPDATE_SINGER_SUCCESS);
            }
            return new CommonResult(200, false, MessageConst.UPDATE_SINGER_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @PostMapping("/update/{id}")
    @ApiOperation("更新歌手图片")
    public CommonResult updateImg(@RequestParam("file") MultipartFile multipartFile, @PathVariable("id") Integer id) {
        if (multipartFile.isEmpty()) {
            return new CommonResult(200, false, MessageConst.UPDATE_SINGER_IMG_FAIL);
        }
        String fileName = System.currentTimeMillis() + multipartFile.getOriginalFilename();
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "img" + System.getProperty("file.separator")
                + "singerPic"; //文件路径
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        //上传后的文件地址
        File realPath = new File(filePath + System.getProperty("file.separator") + fileName);
        try {
            multipartFile.transferTo(realPath);
            Singer singer = singerService.getById(id);
            File picFile = new File(System.getProperty("user.dir") + singer.getPic());
            if (picFile.exists()) {
                picFile.delete();
            }
            singer.setPic("/img/singerPic/" + fileName); //更新数据库文件的相对地址
            if (singerService.updateById(singer)) {
                return new CommonResult(200, true, MessageConst.UPDATE_SINGER_IMG_SUCCESS);
            }
            return new CommonResult(200, false, MessageConst.UPDATE_SINGER_IMG_FAIL);
        } catch (IOException e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @DeleteMapping("/delete/{idx}")
    @ApiOperation("删除歌手")
    public CommonResult delete(@PathVariable("idx") String ids) {
        try {
            for (String id : Arrays.asList(ids)) {
                Singer singer = singerService.getById(Integer.parseInt(id));
                Map<String, Object> map = new HashMap<>();
                map.put("singer_id", Integer.parseInt(id));
                List<Song> songs = songService.listByMap(map);
                if (songs != null && songs.size() > 0) {
                    for (Song song : songs) {
                        Map<String, Object> songMap = new HashMap<>();
                        songMap.put("song_id", song.getId());
                        List<ListSong> listSongs = listSongService.listByMap(songMap);
                        if (listSongs != null && listSongs.size() > 0) {
                            listSongService.removeByMap(songMap);
                        }
                        List<Comment> comments = commentService.listByMap(songMap);
                        if (comments != null && comments.size() > 0) {
                            commentService.removeByMap(songMap);
                        }
                        List<Collect> collects = collectService.listByMap(songMap);
                        if (collects != null && collects.size() > 0) {
                            collectService.removeByMap(songMap);
                        }
                    }
                }
                File picFile = new File(System.getProperty("user.dir") + singer.getPic());
                if (singerService.removeById(id)) {
                    if (picFile.exists()) {
                        picFile.delete();
                    }
                }
            }
            return new CommonResult(200, true, MessageConst.DELETE_SINGER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.DELETE_SINGER_FAIL);
        }
    }

    @GetMapping("/{currentPage}/{pageSize}")
    @ApiOperation("歌手检索")
    public CommonResult findByPageAndParam(@PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize, Singer singer) {
        try {
            Page<Singer> page = singerService.page(new Page<>(currentPage, pageSize), getWrapper(singer));
            if (currentPage > page.getPages()) { //判断当前也是否大于总页数
                return new CommonResult(200, true, singerService.page(new Page<>(page.getPages(), pageSize), getWrapper(singer)));
            }
            return new CommonResult(200, true, singerService.page(new Page<>(currentPage, pageSize), getWrapper(singer)));
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @GetMapping
    @ApiOperation("获取所有歌手信息")
    public CommonResult count() {
        try {
            return new CommonResult(200, true, singerService.list());
        } catch (Exception e) {
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @GetMapping("/{sex}")
    @ApiOperation("根据性别获取歌手信息")
    public CommonResult sex(@PathVariable("sex") String sex) {
        try {
            LambdaQueryWrapper<Singer> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(!StringUtils.isEmpty(sex), Singer::getSex, sex);
            return new CommonResult(200, true, singerService.list(wrapper));
        } catch (Exception e) {
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @GetMapping("/detail/{id}")
    @ApiOperation("根据歌手id获取歌曲信息")
    public CommonResult findById(@PathVariable("id") Integer id) {
        try {
            LambdaQueryWrapper<Song> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(id != null, Song::getSingerId, id);
            return new CommonResult(200, true, songService.list(wrapper));
        } catch (Exception e) {
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    //封装查询条件
    private QueryWrapper<Singer> getWrapper(Singer singer) {
        QueryWrapper<Singer> wrapper = new QueryWrapper<>();
        wrapper.like(!StringUtils.isEmpty(singer.getName()), "name", singer.getName());
        wrapper.like(!StringUtils.isEmpty(singer.getSex()), "sex", singer.getSex());
        wrapper.like(!StringUtils.isEmpty(singer.getLocation()), "location", singer.getLocation());
        return wrapper;
    }
}

